<template>
  <div class="raw-material-wrap">
    <!-- 条件查询区域 -->
    <el-card class="mb16">
      <el-form :model="queryForm" inline :inline-message="true">
        <el-form-item label="采购单号" prop="procureId">
          <el-input
              v-model="queryForm.procureId"
              placeholder="请输入采购单号"
              clearable
              style="width: 180px"
          />
        </el-form-item>

        <el-form-item label="商品" prop="productId">
          <el-select
              v-model="queryForm.productId"
              placeholder="请选择商品"
              clearable
              style="width: 180px"
          >
            <el-option
                v-for="p in getProOpts"
                :key="p.value"
                :label="p.label"
                :value="p.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="供应商" prop="supplierId">
          <el-select
              v-model="queryForm.supplierId"
              placeholder="请选择供应商"
              clearable
              style="width: 180px"
          >
            <el-option
                v-for="s in supplierOpts"
                :key="s.value"
                :label="s.label"
                :value="s.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="仓库" prop="warehouseId">
          <el-select
              v-model="queryForm.warehouseId"
              placeholder="请选择仓库"
              clearable
              style="width: 180px"
          >
            <el-option
                v-for="w in warehouseOpts"
                :key="w.value"
                :label="w.label"
                :value="w.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select
              v-model="queryForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 180px"
          >
            <el-option label="已入库，待付款" value="2" />
            <el-option label="已入库，已付款" value="3" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-row justify="space-between" align="middle" class="mb16">
      <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="size"
          :page-sizes="[5, 10, 20, 50]"
          v-model:current-page="page"
          @current-change="loadData"
          @size-change="handleSizeChange"
          class="pagination"
      />
    </el-row>

    <el-table
        :data="tableData"
        stripe
        v-loading="loading"
        border
        :row-class-name="tableRowClassName"
    >
      <el-table-column prop="materialId" label="ID" width="50" />
      <el-table-column prop="procureId" label="采购单号" width="120" />
      <el-table-column prop="productId" label="商品名称" width="90">
        <template #default="{ row }">
          {{ proMap[row.productId] || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="num" label="数量" width="80" />
      <el-table-column prop="price" label="单价(元)" width="80" />
      <el-table-column prop="totalPrice" label="总价(元)" width="110" />
      <el-table-column prop="warehouseId" label="仓库" width="150">
        <template #default="{ row }">
          {{ warehouseMap[row.warehouseId] || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="supplierId" label="供应商" width="200">
        <template #default="{ row }">
          {{ supplierMap[row.supplierId] || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="130">
        <template #default="{ row }">
          <el-tag :type="statusColor(row.status)">
            {{ statusMap[row.status] || '未知' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="{ row }">
          <el-button
              size="small"
              @click="openEdit(row)"
              :disabled="row.status !== 2"
          >
            编辑
          </el-button>

          <el-popconfirm title="确定删除?" @confirm="handleDelete(row.materialId)">
            <template #reference>
              <el-button
                  size="small"
                  type="danger"
                  :disabled="row.status === 3"
              >
                删除
              </el-button>
            </template>
          </el-popconfirm>

          <el-button
              v-if="row.status === 2"
              size="small"
              type="success"
              @click="pay(row.procureId)"
          >
            付款
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑抽屉 -->
    <el-drawer
        v-model="drawer"
        title="编辑采购付款信息"
        direction="rtl"
        size="420"
        destroy-on-close
        @closed="resetForm"
    >
      <el-form
          ref="formRef"
          :model="form"
          label-width="90px"
          :rules="formRules"
      >
        <el-form-item label="采购单号" prop="procureId">
          <el-select
              v-model="form.procureId"
              placeholder="请选择采购单号"
              clearable
              @change="onProcureChange"
              disabled
          >
            <el-option
                v-for="p in procureList"
                :key="p.procureId"
                :label="p.procureId"
                :value="p.procureId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="商品编号">
          <el-input v-model="form.productId" readonly />
        </el-form-item>
        <el-form-item label="单价">
          <el-input v-model="form.price" readonly />
        </el-form-item>

        <el-form-item label="数量" prop="num">
          <el-input-number
              v-model="form.num"
              :min="0.01"
              :precision="2"
              style="width:100%"
              placeholder="请输入数量"
          />
        </el-form-item>

        <el-form-item label="计量单位" prop="unitId">
          <el-select v-model="form.unitId" placeholder="请选择">
            <el-option v-for="u in unitOpts" :key="u.value" :label="u.label" :value="u.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="员工" prop="employeeId">
          <el-select v-model="form.employeeId" placeholder="请选择">
            <el-option v-for="e in empOpts" :key="e.value" :label="e.label" :value="e.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="仓库" prop="warehouseId">
          <el-select v-model="form.warehouseId" placeholder="请选择">
            <el-option v-for="w in warehouseOpts" :key="w.value" :label="w.label" :value="w.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="供应商" prop="supplierId">
          <el-select v-model="form.supplierId" placeholder="请选择">
            <el-option v-for="s in supplierOpts" :key="s.value" :label="s.label" :value="s.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="2">已入库，待付款</el-radio>
            <el-radio :label="3">已入库，已付款</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="drawer=false">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script>
import { ElMessage, ElLoading } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

// API导入
import {
  update,
  deleteById,
  getUnitOpts,
  getEmpOpts,
  getWarehouseOpts,
  getSupplierOpts,
  getProcureMini, getProOpts, findByCondition2
} from '../../api/wms.js'

const defaultForm = () => ({
  materialId: '',
  procureId: '',
  productId: "",
  num: 0,
  price: "",
  totalPrice: 0,
  unitId: '',
  employeeId: '',
  warehouseId: "",
  supplierId: '',
  status: 0,
})

export default {
  name: 'PayMoney',
  components: {},
  setup() {
    return { Plus }
  },
  data() {
    return {
      allData: [],
      loading: false,
      tableData: [],
      total: 0,
      page: 1,
      size: 5,
      drawer: false,
      form: defaultForm(),
      formRules: {
        procureId: [{ required: true, message: '请选择采购单号', trigger: 'change' }],
        num: [
          { required: true, message: '请输入数量', trigger: 'blur' },
          { type: 'number', min: 0.01, message: '数量不能小于0.01', trigger: 'blur' }
        ],
        unitId: [{ required: true, message: '请选择计量单位', trigger: 'change' }],
        employeeId: [{ required: true, message: '请选择员工', trigger: 'change' }],
        warehouseId: [{ required: true, message: '请选择仓库', trigger: 'change' }],
        supplierId: [{ required: true, message: '请选择供应商', trigger: 'change' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }]
      },
      unitOpts: [],
      empOpts: [],
      warehouseOpts: [],
      supplierOpts: [],
      getProOpts:[],
      // 新增映射对象用于快速查询
      proMap: {},
      warehouseMap: {},
      supplierMap: {},
      statusMap: {  2: '已入库，待付款', 3: '已入库，已付款' },
      procureList: [],
      curProcure: null,
      queryForm: {
        procureId: '',
        productId: null,
        supplierId: null,
        warehouseId: null,
        status: null
      }
    }
  },
  mounted() {
    this.loadProcureMini()
    this.loadSelect()
    this.loadData()
  },
  methods: {
    // 支付
    async pay(id) {
      try {
        console.log(id)
        const res = await this.$store.dispatch('rw/reqPay1', {
          orderId:id
        });
        console.log(res); // "success"
        this.$message.success('支付已发起，请完成跳转');
      } catch (error) {
        console.error('支付失败:', error);
        this.$message.error('支付请求失败');
      }
    },
    async loadSelect() {
      try {
        const [u, e, w, s, p] = await Promise.all([
          getUnitOpts(),
          getEmpOpts(),
          getWarehouseOpts(),
          getSupplierOpts(),
          getProOpts()
        ])
        this.unitOpts = u || []
        this.empOpts = e || []
        this.warehouseOpts = w || []
        this.supplierOpts = s || []
        this.getProOpts = p || []

        // 构建映射对象
        this.proMap = this.getProOpts.reduce((map, item) => {
          map[item.value] = item.label;
          return map;
        }, {})
        this.warehouseMap = this.warehouseOpts.reduce((map, item) => {
          map[item.value] = item.label;
          return map;
        }, {})
        this.supplierMap = this.supplierOpts.reduce((map, item) => {
          map[item.value] = item.label;
          return map;
        }, {})
      } catch (error) {
        ElMessage.error('加载下拉选项失败：' + (error.message || '未知错误'))
      }
    },

    async loadData() {
      this.loading = true;
      try {
        const res = await findByCondition2(this.queryForm);
        this.allData = res?.data?.data || [];
        this.total = this.allData.length;
        const startIndex = (this.page - 1) * this.size;
        const endIndex = startIndex + this.size;
        this.tableData = this.allData.slice(startIndex, endIndex);
      } catch (error) {
        ElMessage.error('加载数据失败：' + (error.message || '未知错误'));
      } finally {
        this.loading = false;
      }
    },

    statusColor(st) {
      const colorMap = { 2: 'warning', 3: 'success' }
      return colorMap[st] || 'info'
    },

    openEdit(row) {
      this.form = { ...row }
      this.drawer = true
    },

    async handleDelete(id) {
      try {
        await deleteById(id)
        ElMessage.success('删除成功')
        this.loadData()
      } catch (error) {
        ElMessage.error('删除失败：' + (error.message || '未知错误'))
      }
    },

    async submit() {
      const formRef = this.$refs.formRef
      if (!formRef) return

      try {
        await formRef.validate()
        // 修复总价类型为数字
        const num = Number(this.form.num) || 0;
        const price = Number(this.form.price) || 0;
        this.form.totalPrice = Number((num * price).toFixed(2))

        await update(this.form)
        ElMessage.success('修改成功')
        this.drawer = false
        this.loadData()
      } catch (error) {
        if (error.name === 'ValidationError') return
        ElMessage.error('修改失败：' + (error.message || '未知错误'))
      }
    },

    resetForm() {
      const formRef = this.$refs.formRef
      if (formRef) formRef.resetFields()
      this.form = defaultForm()
    },

    async loadProcureMini() {
      try {
        this.procureList = await getProcureMini() || []
      } catch (error) {
        ElMessage.error('加载采购单列表失败：' + (error.message || '未知错误'))
      }
    },

    onProcureChange(val) {
      this.curProcure = this.procureList.find(p => p.procureId === val) || null
      if (this.curProcure) {
        this.form.productId = this.curProcure.productId || ''
        this.form.price = this.curProcure.price || 0
        this.form.num = this.curProcure.num || 0
      } else {
        this.form.productId = ''
        this.form.price = 0
        this.form.num = 0
      }
    },

    tableRowClassName({ row }) {
      return `status-${row.status}`;
    },

    handleSizeChange(val) {
      this.size = val;
      this.page = 1;
      this.loadData();
    },

    async handleQuery() {
      this.page = 1;
      this.loadData();
    },

    resetQuery() {
      this.queryForm = {
        procureId: '',
        productId: null,
        supplierId: null,
        warehouseId: null,
        status: null
      };
      this.page = 1;
      this.loadData();
    }
  }
}
</script>

<style scoped>
.raw-material-wrap {
  padding: 16px;
  //background: var(--bg-0);
  min-height: 100%;
}
.mb16 {
  margin-bottom: 16px;
}
:deep(.el-table__cell) {
  padding: 12px 0;
}
:deep(.el-button.is-disabled) {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 行背景色区分状态 */
:deep(.el-table__row) {
  transition: background-color 0.3s;
}

:deep(.el-table__row.status-2) {
  background-color: #fff8e6; /* 待付款 - 浅黄 */
}

:deep(.el-table__row.status-3) {
  background-color: #e6f7ff; /* 已付款 - 浅蓝 */
}
</style>